import { NextRequest, NextResponse } from 'next/server';
import { MonitoredTokenService } from '@/services/token/MonitoredTokenService';

const tokenService = MonitoredTokenService.getInstance();

// GET - 获取监控代币列表
export async function GET(request: NextRequest) {
  try {
    const { searchParams } = new URL(request.url);
    const page = parseInt(searchParams.get('page') || '1');
    const limit = parseInt(searchParams.get('limit') || '50');
    const active = searchParams.get('active');
    
    const stats = await tokenService.getStats();
    
    // 获取代币列表
    const tokens = await tokenService.getActiveTokens();
    
    // 分页处理
    const startIndex = (page - 1) * limit;
    const endIndex = startIndex + limit;
    const paginatedTokens = tokens.slice(startIndex, endIndex);
    
    return NextResponse.json({
      success: true,
      data: {
        tokens: paginatedTokens,
        pagination: {
          page,
          limit,
          total: stats.activeTokens,
          totalPages: Math.ceil(stats.activeTokens / limit),
          hasMore: endIndex < stats.activeTokens
        },
        stats: {
          totalTokens: stats.totalTokens,
          activeTokens: stats.activeTokens,
          lastUpdate: stats.lastUpdate
        }
      },
      timestamp: new Date().toISOString()
    });
    
  } catch (error) {
    console.error('获取监控代币失败:', error);
    return NextResponse.json(
      { 
        success: false, 
        error: error instanceof Error ? error.message : 'Failed to fetch tokens',
        timestamp: new Date().toISOString()
      },
      { status: 500 }
    );
  }
}

// POST - 添加或更新监控代币
export async function POST(request: NextRequest) {
  try {
    const body = await request.json();
    const { tokens } = body;
    
    if (!Array.isArray(tokens)) {
      return NextResponse.json(
        { success: false, error: 'Invalid tokens array' },
        { status: 400 }
      );
    }
    
    const successCount = await tokenService.upsertTokens(tokens);
    
    return NextResponse.json({
      success: true,
      data: {
        message: `成功处理 ${successCount}/${tokens.length} 个代币`,
        successCount,
        totalCount: tokens.length
      },
      timestamp: new Date().toISOString()
    });
    
  } catch (error) {
    console.error('添加/更新监控代币失败:', error);
    return NextResponse.json(
      { 
        success: false, 
        error: error instanceof Error ? error.message : 'Failed to update tokens',
        timestamp: new Date().toISOString()
      },
      { status: 500 }
    );
  }
} 